﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Sbook.Shopping
{
    public class ShoppingCart
    {
        private static ShoppingCart instance = null;
        public static ShoppingCart Instance
        {
            get
            {
                if (instance == null)
                    instance = new ShoppingCart();
                return instance;
            }
        }

        public List<ShoppingItem> Items
        {
            get
            {
                List<ShoppingItem> list = HttpContext.Current.Session["Cart"] as List<ShoppingItem>;
                if (list == null)
                {
                    list = new List<ShoppingItem>();
                    HttpContext.Current.Session["Cart"] = list;
                }
                return list;
            }
            set
            {
                HttpContext.Current.Session["Cart"] = value;
            }

        }

        public void Add(ShoppingItem item)
        {
            // Kiem tra xem san pham da co trong gio hang chu
            // Co thi cong them so luong
            List<ShoppingItem> items = this.Items;

            for (int i = 0; i < items.Count; i++)
            {
                if (item.ProductId == items[i].ProductId)
                {
                    items[i].Quantity += item.Quantity;
                    return;
                }
            }
            // Con chua co dua vao gio hang
            items.Add(item);
        }

        public void Remove(int productId)
        {
            List<ShoppingItem> items = this.Items;

            ShoppingItem item = null;
            for (int i = 0; i < items.Count; i++)
                if (items[i].ProductId == productId)
                    item = items[i];

            if (item != null)
                items.Remove(item);
        }

        public void Update(ShoppingItem item)
        {
            List<ShoppingItem> items = this.Items;

            for (int i = 0; i < items.Count; i++)
            {
                if (item.ProductId == items[i].ProductId)
                {
                    items[i].Quantity = item.Quantity;
                    return;
                }
            }
        }

        public ShoppingItem GetItem(int productId)
        {
            List<ShoppingItem> items = this.Items;

            ShoppingItem item = null;
            for (int i = 0; i < items.Count; i++)
                if (items[i].ProductId == productId)
                    item = items[i];
            if (item == null)
                item = new ShoppingItem();
            return item;
        }
        public decimal PriceTotal()
        {
            decimal Total = 0;
            for (int i = 0; i < this.Items.Count; i++)
                Total += this.Items[i].Price * this.Items[i].Quantity;
            return Total;
        }

    }
}